//
//  ZNWBVisitorView.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/8/3.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit

class ZNWBVisitorView: UIView {
    
    //MARK: - 判断是否是首页
    fileprivate var isHome = false
    
    //MARK: - 访客视图信息
    var visitorInfo: [String: String]? {
        didSet {
            guard let imageName = visitorInfo?["imageName"],
                  let message = visitorInfo?["message"]
            else {
                return
            }
            
            tipLabel.text = message
            
            if imageName == "" {
                startAnimation()
                
                isHome = true
                loginButton.removeFromSuperview()
                registerButton.setTitle("去关注", for: .normal)

                return
            }
            
            iconView.image = UIImage(named: imageName)
            //不能这么做，因为其他控件的布局依赖于它们
//            maskIconView.removeFromSuperview()
//            houseView.removeFromSuperview()
            maskIconView.isHidden = true
            houseView.isHidden = true
        }
    }
    
    //MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 界面布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 1. 取消autoresizing，不与自动布局共存
        // 无效的示例
//        translatesAutoresizingMaskIntoConstraints = false
//        autoresizesSubviews = false
        
        for view in subviews {
            view.translatesAutoresizingMaskIntoConstraints = false
        }
        
        // 2. 为子视图添加约束
        let margin: CGFloat = 20.0
        let buttonWidth: CGFloat = 100.0
        
        // 2.1 圈
        addConstraint(NSLayoutConstraint(
            item: iconView,
            attribute: .centerX,
            relatedBy: .equal,
            toItem: self,
            attribute: .centerX,
            multiplier: 1.0,
            constant: 0))
        addConstraint(NSLayoutConstraint(
            item: iconView,
            attribute: .centerY,
            relatedBy: .equal,
            toItem: self,
            attribute: .centerY,
            multiplier: 1.0,
            constant: -60))
        
        // 2.1 房子
        addConstraint(NSLayoutConstraint(
            item: houseView,
            attribute: .centerX,
            relatedBy: .equal,
            toItem: iconView,
            attribute: .centerX,
            multiplier: 1.0,
            constant: 0))
        addConstraint(NSLayoutConstraint(
            item: houseView,
            attribute: .centerY,
            relatedBy: .equal,
            toItem: iconView,
            attribute: .centerY,
            multiplier: 1.0,
            constant: 0))
        
        // 2.3 标题
        addConstraint(NSLayoutConstraint(
            item: tipLabel,
            attribute: .centerX,
            relatedBy: .equal,
            toItem: iconView,
            attribute: .centerX,
            multiplier: 1.0,
            constant: 0))
        addConstraint(NSLayoutConstraint(
            item: tipLabel,
            attribute: .top,
            relatedBy: .equal,
            toItem: iconView,
            attribute: .bottom,
            multiplier: 1.0,
            constant: margin))
        addConstraint(NSLayoutConstraint(
            item: tipLabel,
            attribute: .width,
            relatedBy: .equal,
            toItem: nil,
            attribute: .notAnAttribute,
            multiplier: 1.0,
            constant: 236))
        
        // 2.4 注册按钮
        if isHome {
            addConstraint(NSLayoutConstraint(item: registerButton, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
           isHome = false
        } else {
            addConstraint(NSLayoutConstraint(
                item: registerButton,
                attribute: .left,
                relatedBy: .equal,
                toItem: tipLabel,
                attribute: .left,
                multiplier: 1.0,
                constant: 0))
            
            // 2.5 登录按钮
            addConstraint(NSLayoutConstraint(
                item: loginButton,
                attribute: .right,
                relatedBy: .equal,
                toItem: tipLabel,
                attribute: .right,
                multiplier: 1.0,
                constant: 0))
            addConstraint(NSLayoutConstraint(item: loginButton, attribute: .top, relatedBy: .equal, toItem: tipLabel, attribute: .bottom, multiplier: 1.0, constant: margin))
            addConstraint(NSLayoutConstraint(
                item: loginButton,
                attribute: .width,
                relatedBy: .equal,
                toItem: nil,
                attribute: .notAnAttribute,
                multiplier: 1.0,
                constant: buttonWidth))
        }
        
        addConstraint(NSLayoutConstraint(item: registerButton, attribute: .top, relatedBy: .equal, toItem: tipLabel, attribute: .bottom, multiplier: 1.0, constant: margin))
        addConstraint(NSLayoutConstraint(
            item: registerButton,
            attribute: .width,
            relatedBy: .equal,
            toItem: nil,
            attribute: .notAnAttribute,
            multiplier: 1.0,
            constant: buttonWidth))
        
        //2.6 利用VFS约束遮罩
        // VFL(visual format language): 可视化格式语言，VFL公式为字符串，赋值给第一个参数，选项设置为空。适用于连续的参照关系
        // H：水平方向 V：垂直方向 |：边界 []：包含控件的名称字符串，映射关系在views字典中设置 ()：定义控件的宽/高，在metrics中映射
        let viewDict: [String: Any] = ["maskIconView": maskIconView,
                        "registerButton": registerButton]
        let metrics = ["spacing": -20]
        
        addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "H:|-0-[maskIconView]-0-|",
            options: [],
            metrics: nil,
            views: viewDict))
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[maskIconView]-(spacing)-[registerButton]", options: [], metrics: metrics, views: viewDict))
    }
    
    //MARK: - 私有视图
    
    // 注册按钮
    lazy var registerButton: UIButton = UIButton.cz_textButton(
        "注册",
        fontSize: 16,
        normalColor: UIColor.orange,
        highlightedColor: UIColor.white,
        backgroundImageName: "common_button_white_disable")
    
    // 登录按钮
    lazy var loginButton: UIButton = UIButton.cz_textButton(
        "登录",
        fontSize: 16,
        normalColor: UIColor.darkGray,
        highlightedColor: UIColor.white,
        backgroundImageName: "common_button_white_disable")
    
    // 圈视图
    fileprivate lazy var iconView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "visitordiscover_feed_image_smallicon"))
    
    // 遮罩
    fileprivate lazy var maskIconView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "visitordiscover_feed_mask_smallicon"))
    
    // 房子视图
    fileprivate lazy var houseView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "visitordiscover_feed_image_house"))
    
    // 提示标签
    fileprivate lazy var tipLabel: UILabel = UILabel.cz_label(
        withText: "",
        fontSize: 14,
        color: UIColor.darkGray)
}

extension ZNWBVisitorView {
    
    fileprivate func setupUI() {
        //使用系统应用/其他/数码测色计获取遮罩的颜色参数（RGB颜色空间，十六进制）
        backgroundColor = UIColor.cz_color(withHex: 0xEDEDED)
        tipLabel.textAlignment = .center
        
        addSubview(iconView)
        addSubview(maskIconView)
        addSubview(houseView)
        addSubview(tipLabel)
        addSubview(registerButton)
        addSubview(loginButton)
    }
    
    fileprivate func startAnimation() {
        let rotation = CABasicAnimation(keyPath: "transform.rotation")
        
        rotation.repeatCount = MAXFLOAT
        rotation.toValue = 2.0 * Double.pi
        rotation.duration = 15.0
        rotation.isRemovedOnCompletion = false
        
        iconView.layer.add(rotation, forKey: "rotation.z")
    }
}
